package com.mingtu.guards.activity;

import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.ha.adapter.AliHaAdapter;
import com.alibaba.ha.adapter.AliHaConfig;
import com.alibaba.ha.adapter.Plugin;
import com.alibaba.ha.adapter.service.tlog.TLogLevel;
import com.alibaba.ha.adapter.service.tlog.TLogService;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.activity.MyCollectActivity;
import com.mingtu.center.activity.MyOffLineMapActivity;
import com.mingtu.center.activity.MyTrackActivity;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.activity.LoginActivity;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.bean.UserInfoBean;
import com.mingtu.common.callback.ResultCallback;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.entity.TabEntity;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.common.view.MultiGridView;
import com.mingtu.common.view.MyDialog;
import com.mingtu.common.viewpager.NoScrollViewPager;
import com.mingtu.liteav2.basic.UserModel;
import com.mingtu.liteav2.basic.UserModelManager;
import com.mingtu.guards.BuildConfig;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.LayerAdapter;
import com.mingtu.guards.adapter.TabbarAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.KeyBean;
import com.mingtu.guards.callback.MyStringDialogCallback;
import com.mingtu.guards.fragment.BioFindFragment;
import com.mingtu.guards.fragment.BioFragment;
import com.mingtu.guards.fragment.IndexFragment3;
import com.mingtu.guards.fragment.LotFragment;
import com.mingtu.guards.fragment.MineFragment;
import com.mingtu.guards.fragment.TrackFragment;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.mingtu.guards.view.FilterAnimalView;
import com.mob.MobSDK;
import com.taobao.sophix.SophixManager;
import com.tencent.aai.AAIClient;
import com.tencent.aai.audio.data.AudioRecordDataSource;
import com.tencent.aai.audio.utils.WavCache;
import com.tencent.aai.auth.AbsCredentialProvider;
import com.tencent.aai.auth.LocalCredentialProvider;
import com.tencent.aai.config.ClientConfiguration;
import com.tencent.aai.exception.ClientException;
import com.tencent.aai.exception.ServerException;
import com.tencent.aai.listener.AudioRecognizeResultListener;
import com.tencent.aai.listener.AudioRecognizeStateListener;
import com.tencent.aai.listener.AudioRecognizeTimeoutListener;
import com.tencent.aai.model.AudioRecognizeRequest;
import com.tencent.aai.model.AudioRecognizeResult;
import com.tencent.aai.model.type.AudioRecognizeConfiguration;
import com.tencent.aai.model.type.AudioRecognizeTemplate;
import com.tencent.aai.model.type.EngineModelType;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.cloud.qcloudasrsdk.recognizer.QCloudOneSentenceRecognizer;
import com.tencent.cloud.qcloudasrsdk.recognizer.QCloudOneSentenceRecognizerAudioPathListener;
import com.tencent.cloud.qcloudasrsdk.recognizer.QCloudOneSentenceRecognizerListener;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMMessageReceipt;
import com.tencent.imsdk.v2.V2TIMSDKConfig;
import com.tencent.imsdk.v2.V2TIMSDKListener;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.DataOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiguang.api.utils.JCollectionAuth;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.ups.JPushUPSManager;

import static com.mingtu.common.utils.Constant.TUI_CALLING_MESSAGE;
import static com.mingtu.guards.base.Application.errorLogFilePath;

@Route(path = "/app/MainActivity")
public class MainActivity extends MyBaseActivity implements QCloudOneSentenceRecognizerListener {


    @BindView(R.id.view_pager)
    NoScrollViewPager viewPager;
    @BindView(R.id.tl)
    CommonTabLayout commonTabLayout;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayoutMap;
    @BindView(R.id.layout_left_drawers)
    LinearLayout layoutLeftDrawers;
    @BindView(R.id.layout_title)
    RelativeLayout layoutTitle;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.mgv)
    MultiGridView mgv;
    @BindView(R.id.rb_map1)
    RadioButton rbMap1;
    @BindView(R.id.rb_map2)
    RadioButton rbMap2;
    @BindView(R.id.rb_map3)
    RadioButton rbMap3;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.tv_off_line)
    TextView tvOffLine;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.status_bar_view_left_drawer)
    View statusBarViewLeftDrawer;
    @BindView(R.id.iv_filte)
    ImageView ivFilte;
    @BindView(R.id.iv_robot_anim)
    ImageView ivRobotAnim;
    @BindView(R.id.iv_voice_anim)
    ImageView ivVoiceAnim;
    @BindView(R.id.tv_voice_info)
    TextView tvVoiceInfo;
    @BindView(R.id.layout_bottom_voice)
    FrameLayout layoutBottomVoice;
    @BindView(R.id.layout_tab)
    FrameLayout layoutTab;
    @BindView(R.id.iv_track)
    ImageView ivTrack;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private TrackFragment tabTrack;
    private static final String[] mTitles = {"首页", "", "我的"};
    private static final int[] mSeleIcons = {R.mipmap.tab1_selected, 0, R.mipmap.tab4_selected};
    private static final int[] mNormalIcons = {R.mipmap.tab1_normal, 0, R.mipmap.tab4_normal};
    private long firstPressedTime;
    private AnimationDrawable robotAnimationDrawable;
    private AnimationDrawable voiceAnimationDrawable;
    private QCloudOneSentenceRecognizer recognizer;
    private Vibrator vibrator;
    private AAIClient aaiClient;
    private int appId = 1259326226;
    private String secretId = "AKID50gvzHQM4e5JK6d0DCwRhmeHftvlOmvp";
    private String secretKey = "iBOM6f06wYyA7sVv78ybz84mFapreCVg";
    private String hoteWordId = "e442816950bd11eca4de446a2eb5fd98";
    private AbsCredentialProvider credentialProvider;
    private AudioRecognizeRequest audioRecognizeRequest;
    private AudioRecognizeConfiguration audioRecognizeConfiguration;
    private boolean isOnSentence = false;
    private boolean voice = false;
    private boolean mIsKickedOffline = false;
    private boolean mIsUserSigExpired = false;
    private String userName;
    private String sdkappid;
    private IndexFragment3 indexFragment3;
    private String mobile;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        //首页
        indexFragment3 = IndexFragment3.getInstance();
        mFragments.add(indexFragment3);


        //巡护
        tabTrack = new TrackFragment();
        mFragments.add(tabTrack);


        //我的
        mFragments.add(new MineFragment());

        viewPager.setOffscreenPageLimit(5);//需要设置此值
        viewPager.setAdapter(new TabbarAdapter(getSupportFragmentManager(), mFragments));

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mSeleIcons[i], mNormalIcons[i]));
        }

        commonTabLayout.setTabData(mTabEntities);
        commonTabLayout.setOnTabSelectListener(onTabSelectListener);
        viewPager.addOnPageChangeListener(onPageChangeListener);
        viewPager.setCurrentItem(0);
        tvTitle.setText(mTitles[0]);


        String geoFenceFlag = SPStaticUtils.getString(SPTools.GeoFenceFlag); //是否是出地理围栏导致的巡护结束 1:巡护时间超过8小时  自动结束  2:超出地理围栏 巡护结束
        if (!StringUtils.isEmpty(geoFenceFlag)) {
            String str = "";
            if (geoFenceFlag.equals(Constant.AUTO_END_TRACK_TYPE_ONE)) {
                str = "巡护时间超出" + MyConstant.TRACK_AUTO_END_TIME / 3600 + "小时，已经自动结束巡护！";
            } else if (geoFenceFlag.equals(Constant.AUTO_END_TRACK_TYPE_TWO)) {
                str = "巡护超出地理围栏，已经自动结束巡护！";
            }
            MyDialog dialog = new MyDialog(MainActivity.this);
            dialog.setMessage(str);
            dialog.setOnSureClickListener(new MyDialog.OnSureClickListener() {
                @Override
                public void onSureClick() {
                    SPStaticUtils.remove(SPTools.GeoFenceFlag);
                    dialog.dismiss();
                }
            });
            dialog.show();
        }


        EventBus.getDefault().register(this);

        //百度统计，上传用户识别ID
        //StatService.setUserId(context, alias + "_" + phone);
//        XGPushConfig.enableDebug(this,true);
//        XGPushManager.registerPush(this, new XGIOperateCallback() {
//            @Override
//            public void onSuccess(Object data, int flag) {
//                //token在设备卸载重装的时候有可能会变
//                Log.d("TPush", "注册成功，设备token为：" + data);
//            }
//
//            @Override
//            public void onFail(Object data, int errCode, String msg) {
//                Log.d("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
//            }
//        });

        initIMListener();
//        initChannel();

        List<String> tags = new ArrayList<>();
        mobile = SPStaticUtils.getString(SPTools.mobile);//联系方式
        userName = SPStaticUtils.getString(SPTools.userName);//联系方式
        if (!StringUtils.isEmpty(mobile)) {
            tags.add(mobile);
        }

        SophixManager.getInstance().setTags(tags); //设置灰度发布的标签，需要在queryAndLoadNewPatch之前调用
        //加载补丁包
        SophixManager.getInstance().queryAndLoadNewPatch();
        //TLog远程日志
        initHa(mobile, userName);
        initPolicyGrant();
        //腾讯浏览服务
        initQb();

        if (JPushInterface.isPushStopped(context)) {
            JPushUPSManager.turnOnPush(context, null);
        }

        getUserInfo();

    }

    //隐私声明
    private void initPolicyGrant() {
        MobSDK.submitPolicyGrantResult(true);

        //关闭SDK自启动,为了上架审核，不影响推送
//        JCollectionAuth.enableAutoWakeup(context, false);
        JPushInterface.setDebugMode(AppUtils.isAppDebug());
        JCollectionAuth.setAuth(this, true);
        JPushInterface.init(this);

        StatService.setAuthorizedState(this, true);

        //bugly
        CrashReport.initCrashReport(getApplicationContext(), "05e8d5c621", false);
        CrashReport.setDeviceId(context, DeviceUtils.getUniqueDeviceId()); // 设备id
        CrashReport.setDeviceModel(context, DeviceUtils.getModel()); //设备型号
        CrashReport.setAppVersion(context, AppUtils.getAppVersionName());
        CrashReport.setAppPackage(context, AppUtils.getAppPackageName());
    }


    private void initQb() {
        /* 设置允许移动网络下进行内核下载。默认不下载，会导致部分一直用移动网络的用户无法使用x5内核 */
        QbSdk.setDownloadWithoutWifi(true);

        /* SDK内核初始化周期回调，包括 下载、安装、加载 */
        QbSdk.setTbsListener(new TbsListener() {

            /**
             * @param stateCode 110: 表示当前服务器认为该环境下不需要下载
             */
            @Override
            public void onDownloadFinish(int stateCode) {
                MyLogUtil.i("QbSdk", "onDownloadFinished: " + stateCode);
            }

            /**
             * @param stateCode 200、232安装成功
             */
            @Override
            public void onInstallFinish(int stateCode) {
                MyLogUtil.i("QbSdk", "onInstallFinished: " + stateCode);
            }

            /**
             * 首次安装应用，会触发内核下载，此时会有内核下载的进度回调。
             * @param progress 0 - 100
             */
            @Override
            public void onDownloadProgress(int progress) {
                MyLogUtil.i("QbSdk", "Core Downloading: " + progress);
            }
        });

        /* 此过程包括X5内核的下载、预初始化，接入方不需要接管处理x5的初始化流程，希望无感接入 */
        QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                // 内核初始化完成，可能为系统内核，也可能为系统内核
            }

            /**
             * 预初始化结束
             * 由于X5内核体积较大，需要依赖wifi网络下发，所以当内核不存在的时候，默认会回调false，此时将会使用系统内核代替
             * 内核下发请求发起有24小时间隔，卸载重装、调整系统时间24小时后都可重置
             * @param isX5 是否使用X5内核
             */
            @Override
            public void onViewInitFinished(boolean isX5) {
//                MyLogUtil.i(TAG, "onViewInitFinished: " + isX5);
            }
        });
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(statusBarView);
        StatusBarUtil.addStatusBarHeight(statusBarViewLeftDrawer);
        //沉侵式状态栏
        ImmersionBar immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(true);  //状态栏字体是深色，不写默认为亮色
        immersionBar.init();

        layoutTitle.setVisibility(View.GONE);
        statusBarView.setVisibility(View.GONE);

        drawerLayoutMap.setDrawerListener(new MyDrawerListener());

        //图层
        LayerAdapter adapter = new LayerAdapter(context, mgv);
        mgv.setAdapter(adapter);
        adapter.setOnItemClickListener(new LayerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, boolean isChecked) {
                closeDrawers();
                tabTrack.menuEnevt(position, !isChecked);
            }
        });


    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void getData() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_map1: //普通地图
                        tabTrack.setMapType(0);
                        break;
                    case R.id.rb_map2://卫星地图
                        tabTrack.setMapType(1);
                        break;
                    case R.id.rb_map3://谷歌地图
                        tabTrack.setMapType(2);
                        break;


                }
            }
        });

        robotAnimationDrawable = (AnimationDrawable) ivRobotAnim.getBackground();
        voiceAnimationDrawable = (AnimationDrawable) ivVoiceAnim.getBackground();
        ivRobotAnim.setOnTouchListener(new MyOnTouchListener());
        vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);   //获取系统的Vibrator服务

        //一句话语音识别
        if (isOnSentence) {
            initOneSentenceRecognize();
        } else {
            handler = new Handler(getMainLooper());
            initRealtimeRecognize();
        }
        robotAnimStart();

        //上传捕获的错误日志
        if (FileUtils.isFile(errorLogFilePath())) {
            byte[] bytes = FileIOUtils.readFile2BytesByChannel(errorLogFilePath());
            String string = new String(bytes);
            uploadErrorLog(string);
        }

    }


    @OnClick({R.id.tv_off_line, R.id.iv_track})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_off_line:
                IntentUtils.getInstance().readyGo(MainActivity.this, MyOffLineMapActivity.class);
                break;
            case R.id.iv_track:
                layoutTitle.setVisibility(View.VISIBLE);
                statusBarView.setVisibility(View.VISIBLE);
                isShowVoiceRobot(false);
                viewPager.setCurrentItem(1, false);
                tvTitle.setText("资源地图");
                if (!XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) ||
                        !XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {
                    new XPopup.Builder(MainActivity.this)
                            .isDestroyOnDismiss(true)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(true)
                            .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_location_storage_auth),
                                    context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            tabTrack.locationPermissions();
                                        }
                                    }, null, false)
                            .show();
                } else {
                    if (!XXPermissions.isGranted(this, Permission.SYSTEM_ALERT_WINDOW)) {
                        new XPopup.Builder(MainActivity.this)
                                .isDestroyOnDismiss(true)
                                .dismissOnTouchOutside(true)
                                .hasShadowBg(true)
                                .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_float_auth),
                                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                        new OnConfirmListener() {
                                            @Override
                                            public void onConfirm() {
                                                tabTrack.floatPermissions();
                                            }
                                        }, null, false)
                                .show();
                    }
                }


                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 点击手机上的返回键，返回上一层
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - firstPressedTime < 2000) {
                ActivityUtil.removeAllActivity();
            } else {
                ToastUtils.showLong("再按一次退出");
                firstPressedTime = System.currentTimeMillis();
            }
        }
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (robotAnimationDrawable != null) {
            robotAnimStop();
        }

        if (aaiClient != null) {
            aaiClient.cancelAudioRecognize(currentRequestId);
        }


        deleteCacheVoice();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        robotAnimStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (recognizer != null) {
            recognizer.unBindAudioAudioService();
        }
        if (robotAnimationDrawable != null) {
            robotAnimStop();
        }

        if (aaiClient != null) {
            aaiClient.release();
        }

        EventBus.getDefault().unregister(this);

        //识别结束之后删除缓存的文件

        deleteCacheVoice();

    }

    @Override
    public void onNetChange(boolean netWorkState) {
        super.onNetChange(netWorkState);
        try {
            tabTrack.setNetWorkState(netWorkState);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) ||
                    XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {
                //获取到GPS 权限
                tabTrack.initGpsStatus();
            } else {
                ToastUtils.showLong("GPS权限获取失败！");
            }
            if (!XXPermissions.isGranted(this, Permission.NOTIFICATION_SERVICE)) {
                //通知权限
                ToastUtils.showLong("通知权限获取失败！");
            }

            if (!XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE) || !XXPermissions.isGranted(this, Permission.READ_EXTERNAL_STORAGE)) {
                //通知权限
                ToastUtils.showLong("存储权限获取失败！");
            }

            if (!XXPermissions.isGranted(this, Permission.RECORD_AUDIO)) {
                //通知权限
                ToastUtils.showLong("录音权限获取失败！");
            }
        }
    }

    /**
     * 下面三个是[一句话语音识别]录音相关的监听
     */

    @Override
    public void didStartRecord() {
        //开始录音
        MyLogUtil.e("voice", "didStartRecord..");
        voiceAnimStart();

    }

    @Override
    public void didStopRecord() {
        //停止录音
        MyLogUtil.e("voice", "didStopRecord..");
        voiceAnimStop();

    }

    @Override
    public void recognizeResult(QCloudOneSentenceRecognizer qCloudOneSentenceRecognizer, String result, Exception exception) {
        //识别回调
        //1. 回到首页
        //2. 切换到金刚台林场
        //3. 切换到金刚台保护区
        //4. 切换到鲇鱼山保护区
        //5. 切换到金刚台地址公园
        //6. 切换到生态监测
        //7. 切换到智能巡护
        //8. 切换到无人机监测
        //9. 切换到红外监测
        //10. 切换到生物监测
        if (exception != null) {
            MyLogUtil.e("voice", "recognizeResult result: " + result + "exception msg" + exception + exception.getLocalizedMessage());
        } else {
            MyLogUtil.e("voice", "recognizeResult result: " + result);

//            if (StringUtils.isEmpty(result)) {
//                ToastUtils.showLong("主人，请说话哦~");
//                return;
//            }
//            if (result.indexOf("首页") != -1) {
//                voiceSend("index");
//            } else if (result.indexOf("金刚台林场") != -1) {
//                voiceSend("jgtlc");
//            } else if (result.indexOf("金刚台保护区") != -1) {
//                voiceSend("jgtbhq");
//            } else if (result.indexOf("金刚台地质公园") != -1) {
//                voiceSend("jgtdzgy");
//            } else if (result.indexOf("鲇鱼山") != -1) {
//                voiceSend("nysbhq");
//            } else if (result.indexOf("生态监测") != -1) {
//                voiceSend("stjc");
//            } else if (result.indexOf("智能巡护") != -1) {
//                voiceSend("znxh");
//            } else if (result.indexOf("无人机监测") != -1) {
//                voiceSend("wrjjc");
//            } else if (result.indexOf("红外监测") != -1) {
//                voiceSend("hwjc");
//            } else if (result.indexOf("生物监测") != -1) {
//                voiceSend("swjc");
//            }
        }

    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {

    }

    private class MyDrawerListener implements DrawerLayout.DrawerListener {

        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {
            //打开左边栏


        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {
            //关闭左边栏

        }

        @Override
        public void onDrawerStateChanged(int newState) {

        }
    }

    private class MyOnTouchListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent e) {
            // 拦截底部布局的点击事件 返回值为true 消费事件
            switch (e.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    //开始录音
                    XXPermissions.with(MainActivity.this)
                            .permission(Permission.RECORD_AUDIO)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (permissions.contains(Permission.RECORD_AUDIO)) {
                                        if (vibrator != null) {
                                            vibrator.vibrate(150);
                                        }

                                        if (isOnSentence) {

                                            /**
                                             * setDefaultParams 默认参数param
                                             * @param filterDirty    0 ：默认状态 不过滤脏话 1：过滤脏话
                                             * @param filterModal    0 ：默认状态 不过滤语气词  1：过滤部分语气词 2:严格过滤
                                             * @param filterPunc     0 ：默认状态 不过滤句末的句号 1：滤句末的句号
                                             * @param convertNumMode 1：默认状态 根据场景智能转换为阿拉伯数字；0：全部转为中文数字。
                                             * @param hotwordId  热词id，不使用则传null
                                             */
                                            try {
                                                if (recognizer != null) {
                                                    recognizer.setDefaultParams(0, 0, 1, 1, hoteWordId);
                                                    recognizer.recognizeWithRecorder();
                                                    recognizer.setQCloudOneSentenceRecognizerAudioPathListener(new QCloudOneSentenceRecognizerAudioPathListener() {
                                                        @Override
                                                        public void callBackAudioPath(String audioPath) {
                                                            MyLogUtil.e("voice", "callBackAudioPath: audioPath=" + audioPath);

                                                        }
                                                    });
                                                }
                                            } catch (Exception ex) {
                                                ex.printStackTrace();
                                            }
                                        } else {

                                            if (aaiClient != null) {
                                                boolean taskExist = aaiClient.cancelAudioRecognize(currentRequestId);
                                                MyLogUtil.e("voice", " ACTION_DOWN taskExist=" + taskExist);
                                            }

                                            MyLogUtil.e("voice", "the start button has clicked..");
                                            resMap.clear();
                                            handler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    voiceAnimStart();
                                                }
                                            });
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    aaiClient.startAudioRecognize(audioRecognizeRequest,
                                                            new MyAudioRecognizeResultlistener(),
                                                            new MyAudioRecognizeStateListener(),
                                                            new MyAudioRecognizeTimeoutListener(),
                                                            audioRecognizeConfiguration);

                                                }
                                            }).start();
                                        }

                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (never) {
                                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                        new XPopup.Builder(MainActivity.this)
                                                .isDestroyOnDismiss(true)
                                                .dismissOnTouchOutside(true)
                                                .hasShadowBg(true)
                                                .asConfirm(context.getResources().getString(R.string.text_tip), "请手动授予录音权限",
                                                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                                        new OnConfirmListener() {
                                                            @Override
                                                            public void onConfirm() {
                                                                XXPermissions.startPermissionActivity(MainActivity.this, permissions);
                                                            }
                                                        }, null, false)
                                                .show();
                                    } else {

                                    }

                                }
                            });


                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                    //录音结束
                    if (isOnSentence) {
                        if (recognizer != null) {
                            recognizer.stopRecognizeWithRecorder();
                        }
                    } else {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                boolean taskExist = false;
                                if (aaiClient != null) {
                                    taskExist = aaiClient.stopAudioRecognize(currentRequestId);
                                    MyLogUtil.e("voice", " ACTION_UP taskExist=" + taskExist);
                                }
                                if (!taskExist) {
//                                    handler.post(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            voiceAnimStop();
//
//                                        }
//                                    });
                                }
                            }
                        }).start();


                    }
                    break;

            }
            return true;
        }
    }

    /**
     * 隐藏底部tab
     */
    public void hideBottomTab() {
        layoutTab.setVisibility(View.GONE);
        ivTrack.setVisibility(View.GONE);
    }


    /**
     * 显示底部tab
     */
    public void showBottomTab() {
        layoutTab.setVisibility(View.VISIBLE);
        ivTrack.setVisibility(View.VISIBLE);
    }


    /**
     * 关闭左侧边栏
     */
    public void closeDrawers() {
        drawerLayoutMap.closeDrawer(layoutLeftDrawers);
    }

    /**
     * 打开左侧边栏
     */
    public void openDrawer() {
        drawerLayoutMap.openDrawer(layoutLeftDrawers);
    }


    private OnTabSelectListener onTabSelectListener = new OnTabSelectListener() {
        @Override
        public void onTabSelect(int position) {
            viewPager.setCurrentItem(position, false);
            tvTitle.setText(mTitles[position]);
            if (position == 1) {
                drawerLayoutMap.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            } else {
                drawerLayoutMap.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

            }

            layoutTitle.setVisibility(View.GONE);
            statusBarView.setVisibility(View.GONE);

            if (position == 1) {
                layoutTitle.setVisibility(View.VISIBLE);
                statusBarView.setVisibility(View.VISIBLE);
            } else {
                layoutTitle.setVisibility(View.GONE);
                statusBarView.setVisibility(View.GONE);
            }

            if (position == 1) {
                openDrawer();
            } else {
                closeDrawers();
            }

            //语音机器人显示逻辑
            if (position == 0) {
                isShowVoiceRobot(true);
                ImmersionBar immersionBar = ImmersionBar.with(MainActivity.this);
                immersionBar.statusBarDarkFont(true);  //状态栏字体是深色，不写默认为亮色
                immersionBar.init();
            } else {
                isShowVoiceRobot(false);
                ImmersionBar immersionBar = ImmersionBar.with(MainActivity.this);
                immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
                immersionBar.init();
            }

        }

        @Override
        public void onTabReselect(int position) {

        }
    };

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            //语音机器人显示逻辑
            if (position == 0) {
                isShowVoiceRobot(true);
            } else {
                isShowVoiceRobot(false);
            }
        }

        @Override
        public void onPageSelected(int position) {
            //语音机器人显示逻辑
            commonTabLayout.setCurrentTab(position);
            tvTitle.setText(mTitles[position]);

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };


    /**
     * 是否显示语音机器人
     */
    private void isShowVoiceRobot(boolean isShowVoiceRobot) {
        if (voice) {
            if (isShowVoiceRobot) { //语音控制按钮有权限设置
                ivRobotAnim.setVisibility(View.VISIBLE);
            } else {
                ivRobotAnim.setVisibility(View.GONE);
            }
        }
    }


    /**
     * 机器人动画
     */
    private void robotAnimStart() {
        robotAnimationDrawable.start();
    }

    private void robotAnimStop() {
        robotAnimationDrawable.stop();
    }

    /**
     * 语音动画
     */
    private void voiceAnimStart() {
        layoutBottomVoice.setVisibility(View.VISIBLE);
        voiceAnimationDrawable.start();
    }

    private void voiceAnimStop() {
        layoutBottomVoice.setVisibility(View.GONE);
        voiceAnimationDrawable.stop();
    }

    /**
     * 删除缓存的音频文件
     */
    private void deleteCacheVoice() {
        //识别结束之后删除缓存的文件
        String path = getCacheDir().getPath() + "/QCloudRecord";
        boolean isDir = FileUtils.isDir(path);
        if (isDir) {
            FileUtils.delete(path);
        }
    }

    /**
     * 初始化一句话语音识别
     */

    private void initOneSentenceRecognize() {
        if (recognizer == null) {
            /**直接鉴权**/
            recognizer = new QCloudOneSentenceRecognizer(this, appId + "", secretId, secretKey);
            recognizer.setCallback(this);
        }
    }

    /**
     * 初始化时实语音识别
     */

    final int projectId = 0;
    private LinkedHashMap<String, String> resMap = new LinkedHashMap<>();
    private Handler handler;
    private static final Logger logger = LoggerFactory.getLogger(MainActivity.class);
    private int currentRequestId = 0;
    boolean isSaveAudioRecordFiles = true;

    private void initRealtimeRecognize() {
        credentialProvider = new LocalCredentialProvider(secretKey);
        ClientConfiguration.setMaxAudioRecognizeConcurrentNumber(2); // 语音识别的请求的最大并发数 (1-5)
        ClientConfiguration.setMaxRecognizeSliceConcurrentNumber(5); // 单个请求的分片最大并发数(1-5)
        if (aaiClient == null) {
            try {
                /**直接鉴权**/
                aaiClient = new AAIClient(MainActivity.this, appId, projectId, secretId, secretKey, credentialProvider);
                /**使用临时密钥鉴权
                 * * 1.通过sts 获取到临时证书 （secretId secretKey  token） ,此步骤应在您的服务器端实现，见https://cloud.tencent.com/document/product/598/33416
                 *   2.通过临时密钥调用接口
                 * **/
                // aaiClient = new AAIClient(MainActivity.this, appid, projectId,"临时secretId", "临时secretKey","对应的token" ,credentialProvider);

            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
        AudioRecognizeRequest.Builder builder = new AudioRecognizeRequest.Builder();
        audioRecognizeRequest = builder
//                        .pcmAudioDataSource(new AudioRecordDataSource()) // 设置数据源
                .pcmAudioDataSource(new AudioRecordDataSource(isSaveAudioRecordFiles)) // 设置数据源
                //.templateName(templateName) // 设置模板
                .template(new AudioRecognizeTemplate(EngineModelType.EngineModelType16K.getType(), 0)) // 设置自定义模板
                .setFilterDirty(0)  // 0 ：默认状态 不过滤脏话 1：过滤脏话
                .setFilterModal(0) // 0 ：默认状态 不过滤语气词  1：过滤部分语气词 2:严格过滤
                .setFilterPunc(0) // 0 ：默认状态 不过滤句末的句号 1：滤句末的句号
                .setConvert_num_mode(1) //1：默认状态 根据场景智能转换为阿拉伯数字；0：全部转为中文数字。
//                        .setVadSilenceTime(1000) // 语音断句检测阈值，静音时长超过该阈值会被认为断句（多用在智能客服场景，需配合 needvad = 1 使用） 默认不传递该参数
                .setNeedvad(1) //0：关闭 vad，1：默认状态 开启 vad。
                .setHotWordId(hoteWordId)//热词 id。用于调用对应的热词表，如果在调用语音识别服务时，不进行单独的热词 id 设置，自动生效默认热词；如果进行了单独的热词 id 设置，那么将生效单独设置的热词 id。
                .build();

        // 自定义识别配置
        audioRecognizeConfiguration = new AudioRecognizeConfiguration.Builder()
                .setSilentDetectTimeOut(true)// 是否使能静音检测，true表示不检查静音部分
                .audioFlowSilenceTimeOut(5000) // 静音检测超时停止录音
                .minAudioFlowSilenceTime(2000) // 语音流识别时的间隔时间
                .minVolumeCallbackTime(80) // 音量回调时间
                .build();
    }

    private String buildMessage(Map<String, String> msg) {

        StringBuffer stringBuffer = new StringBuffer();
        Iterator<Map.Entry<String, String>> iter = msg.entrySet().iterator();
        while (iter.hasNext()) {
            String value = iter.next().getValue();
            stringBuffer.append(value + "\r\n");
        }
        return stringBuffer.toString();
    }


    /**
     * 识别结果回调监听器
     */
    private class MyAudioRecognizeResultlistener implements AudioRecognizeResultListener {

        boolean dontHaveResult = true;

        /**
         * 返回分片的识别结果
         *
         * @param request 相应的请求
         * @param result  识别结果
         * @param seq     该分片所在语音流的序号 (0, 1, 2...)
         */
        @Override
        public void onSliceSuccess(AudioRecognizeRequest request, AudioRecognizeResult result, int seq) {

            if (dontHaveResult && !TextUtils.isEmpty(result.getText())) {
                dontHaveResult = false;
                Date date = new Date();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                String time = format.format(date);
                String message = String.format("voice flow order = %d, receive first response in %s, result is = %s", seq, time, result.getText());
            }

            MyLogUtil.e("voice", "分片on slice success..");
            MyLogUtil.e("voice", "分片slice seq = " + seq + ",voiceid==" + result.getVoiceId() + ",result ==" + result.getText());
            resMap.put(String.valueOf(seq), result.getText());
            final String msg = buildMessage(resMap);
            MyLogUtil.e("voice", "分片slice msg=" + msg);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    tvVoiceInfo.setText(msg + "");
                }
            });

        }

        /**
         * 返回语音流的识别结果
         *
         * @param request 相应的请求
         * @param result  识别结果
         * @param seq     该语音流的序号 (1, 2, 3...)
         */
        @Override
        public void onSegmentSuccess(AudioRecognizeRequest request, AudioRecognizeResult result, int seq) {
            dontHaveResult = true;
            MyLogUtil.e("voice", "语音流on segment success");
            MyLogUtil.e("voice", "语音流segment seq = " + seq + ",voiceid==" + result.getVoiceId() + ",result ==" + result.getText());
            resMap.put(String.valueOf(seq), result.getText());
            final String msg = buildMessage(resMap);
            MyLogUtil.e("voice", "语音流segment msg=" + msg);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    tvVoiceInfo.setText(msg + "");
                }
            });
        }

        /**
         * 识别结束回调，返回所有的识别结果
         *
         * @param request 相应的请求
         * @param result  识别结果
         */
        @Override
        public void onSuccess(AudioRecognizeRequest request, String result) {
            MyLogUtil.e("voice", "识别结束, onSuccess..");
            MyLogUtil.e("voice", "识别结束, result = " + result);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    tvVoiceInfo.setText(result + "");
                    voiceAnimStop();

                    if (StringUtils.isEmpty(result)) {
                        ToastUtils.showLong("主人，请说话哦~");
                        return;
                    }
                    if (result.indexOf("首页") != -1) {
                        voiceSend("index");
                    } else if (result.indexOf("科研监测") != -1) {
                        voiceSend("kyjc");
                    } else if (result.indexOf("森林防火") != -1) {
                        voiceSend("slfh");
                    } else if (result.indexOf("林场") != -1) {
                        voiceSend("lc");
                    } else if (result.indexOf("保护站") != -1) {
                        voiceSend("bhz");
                    } else if (result.indexOf("视频监控") != -1) {
                        voiceSend("spjk");
                    } else if (result.indexOf("生态旅游") != -1) {
                        voiceSend("stly");
                    } else if (result.indexOf("生态监测") != -1) {
                        voiceSend("stjc");
                    } else if (result.indexOf("智能巡护") != -1) {
                        voiceSend("znxh");
                    } else if (result.indexOf("无人机监测") != -1) {
                        voiceSend("wrjjc");
                    } else if (result.indexOf("红外监测") != -1) {
                        voiceSend("hwjc");
                    } else if (result.indexOf("生物监测") != -1) {
                        voiceSend("swjc");
                    }

                }
            });
        }

        /**
         * 识别失败
         *
         * @param request         相应的请求
         * @param clientException 客户端异常
         * @param serverException 服务端异常
         */
        @Override
        public void onFailure(AudioRecognizeRequest request, final ClientException clientException, final ServerException serverException) {
            handler.post(new Runnable() {
                @Override
                public void run() {

                    if (clientException != null) {
                        String failMessage = clientException.toString();
                        if (failMessage.indexOf("-211") != -1) {
                            ToastUtils.showLong("识别状态：失败,  网络异常！");
                        } else if (failMessage.indexOf("-202") != -1) {
                            ToastUtils.showLong("识别状态：失败, 请求太过频繁");
                        } else {
                            ToastUtils.showLong("识别状态：失败,  " + failMessage);
                        }
                        MyLogUtil.e("voice", "识别状态：失败,  " + clientException.toString());
                    } else if (serverException != null) {
                        String failMessage = serverException.toString();
                        if (failMessage.indexOf("-211") != -1) {
                            ToastUtils.showLong("识别状态：失败,  网络异常！");
                        } else if (failMessage.indexOf("-202") != -1) {
                            ToastUtils.showLong("识别状态：失败, 请求太过频繁");
                        } else {
                            ToastUtils.showLong("识别状态：失败,  " + failMessage);

                        }
                        MyLogUtil.e("voice", "识别状态：失败, , " + serverException.toString());
                    }
                }
            });
        }
    }

    /**
     * 识别状态监听器
     */
    private class MyAudioRecognizeStateListener implements AudioRecognizeStateListener {

        DataOutputStream dataOutputStream;
        String fileName = null;
        String filePath = null;
        ExecutorService mExecutorService;

        /**
         * 开始录音
         *
         * @param request
         */
        @Override
        public void onStartRecord(AudioRecognizeRequest request) {
            currentRequestId = request.getRequestId();
            MyLogUtil.e("voice", "onStartRecord.." + "currentRequestId==" + currentRequestId);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    tvVoiceInfo.setText("");
                }
            });
            //为本次录音创建缓存一个文件
            if (isSaveAudioRecordFiles) {
                if (mExecutorService == null) {
                    mExecutorService = Executors.newSingleThreadExecutor();
                }
                filePath = getCacheDir().getPath() + "/QCloudRecord";
                fileName = System.currentTimeMillis() + ".pcm";
                dataOutputStream = WavCache.creatPmcFileByPath(filePath, fileName);
            }

        }

        /**
         * 结束录音
         *
         * @param request
         */
        @Override
        public void onStopRecord(AudioRecognizeRequest request) {
            MyLogUtil.e("voice", "onStopRecord..");
            handler.post(new Runnable() {
                @Override
                public void run() {
                    voiceAnimStop();
                }
            });
            if (isSaveAudioRecordFiles) {
                mExecutorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        WavCache.closeDataOutputStream(dataOutputStream);
                        WavCache.makePCMFileToWAVFile(filePath, fileName);
                    }
                });

            }

        }

        /**
         * 返回音频流，
         * 用于返回宿主层做录音缓存业务。
         * 由于方法跑在sdk线程上，这里多用于文件操作，宿主需要新开一条线程专门用于实现业务逻辑
         *
         * @param audioDatas
         */
        @Override
        public void onNextAudioData(final short[] audioDatas, final int readBufferLength) {
            if (isSaveAudioRecordFiles) {
                mExecutorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        WavCache.savePcmData(dataOutputStream, audioDatas, readBufferLength);
                    }
                });
            }
        }

        /**
         * 第seq个语音流开始识别
         *
         * @param request
         * @param seq
         */
        @Override
        public void onVoiceFlowStartRecognize(AudioRecognizeRequest request, int seq) {


            MyLogUtil.e("voice", "onVoiceFlowStartRecognize.. seq = " + seq);
            handler.post(new Runnable() {
                @Override
                public void run() {
//                    recognizeState.setText(getString(R.string.start_recognize));
                }
            });
        }

        /**
         * 第seq个语音流结束识别
         *
         * @param request
         * @param seq
         */
        @Override
        public void onVoiceFlowFinishRecognize(AudioRecognizeRequest request, int seq) {

            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            String time = format.format(date);
            String message = String.format("voice flow order = %d, recognize finish in %s", seq, time);

            MyLogUtil.e("voice", "onVoiceFlowFinishRecognize.. seq = " + seq);
            handler.post(new Runnable() {
                @Override
                public void run() {
//                    recognizeState.setText(getString(R.string.end_recognize));

                }
            });
        }

        /**
         * 第seq个语音流开始
         *
         * @param request
         * @param seq
         */
        @Override
        public void onVoiceFlowStart(AudioRecognizeRequest request, int seq) {

            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            String time = format.format(date);
            String message = String.format("voice flow order = %d, start in %s", seq, time);

            MyLogUtil.e("voice", "onVoiceFlowStart.. seq = {}" + seq);

            handler.post(new Runnable() {
                @Override
                public void run() {
//                    recognizeState.setText(getString(R.string.start_voice));
                }
            });
        }

        /**
         * 第seq个语音流结束
         *
         * @param request
         * @param seq
         */
        @Override
        public void onVoiceFlowFinish(AudioRecognizeRequest request, int seq) {

            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            String time = format.format(date);
            String message = String.format("voice flow order = %d, stop in %s", seq, time);

            MyLogUtil.e("voice", "onVoiceFlowFinish.. seq = {}" + seq);
            handler.post(new Runnable() {
                @Override
                public void run() {
//                    recognizeState.setText(getString(R.string.end_voice));
                }
            });
        }

        /**
         * 语音音量回调
         *
         * @param request
         * @param volume
         */
        @Override
        public void onVoiceVolume(AudioRecognizeRequest request, final int volume) {
            MyLogUtil.e("voice", "onVoiceVolume..");
            handler.post(new Runnable() {
                @Override
                public void run() {
//                    MainActivity.this.volume.setText(getString(R.string.volume)+volume);
                }
            });
        }
    }

    /**
     * 识别超时监听器
     */
    private class MyAudioRecognizeTimeoutListener implements AudioRecognizeTimeoutListener {

        /**
         * 检测第一个语音流超时
         *
         * @param request
         */
        @Override
        public void onFirstVoiceFlowTimeout(AudioRecognizeRequest request) {
            handler.post(new Runnable() {
                @Override
                public void run() {
//                    recognizeState.setText(getString(R.string.start_voice_timeout));
                    ToastUtils.showLong("开始说话超时哦！");
                }
            });
        }

        /**
         * 检测下一个语音流超时
         *
         * @param request
         */
        @Override
        public void onNextVoiceFlowTimeout(AudioRecognizeRequest request) {
            handler.post(new Runnable() {
                @Override
                public void run() {
//                    recognizeState.setText(getString(R.string.end_voice_timeout));
                    ToastUtils.showLong("结束说话超时哦！");
                }
            });
        }

    }

    /**
     * 发送大屏控制
     */
    private void voiceSend(String controlType) {
        OkGo.<String>post(MyConstant.POST_VOICE_SEND + "/" + controlType)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("控制命令发送成功！");
                            } else {
                                ToastUtils.showLong("控制命令发送失败！");
                            }
                        }
                    }
                });
    }

    /**
     * 上传错误日志
     *
     * @param errorLog
     */
    public void uploadErrorLog(String errorLog) {
        BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
        String deviceName = myDevice.getName();
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appVersion", "dbspatrol-v" + AppUtils.getAppVersionName());
        hashMap.put("createTime", MyUtills.stampToDateTime2(timeInMillis + ""));
        hashMap.put("mobileModel", deviceName);
        hashMap.put("osVersion", "Android" + DeviceUtils.getSDKVersionName());
        hashMap.put("errorLog", errorLog);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.GET_ERROR_LOG)
                .tag(this)
                .upJson(str)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            FileUtils.delete(errorLogFilePath());
                        }
                    }
                });
    }

    //用于兼容登录过的用户
    private void getUserInfo() {
        OkGo.<String>get(Constant.getInstance().GET_USER_INFO)
                .tag(this)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                UserInfoBean userInfoBean = new UserInfoBean();
                                userInfoBean = gson.fromJson(result, UserInfoBean.class);

                                UserInfoBean.UserBean userBean = userInfoBean.getUser();
                                String username = userBean.getUsername();
                                String mobile = userBean.getMobile();
                                String name = userBean.getName();

                                List<String> isLeaderList = new ArrayList<>();
                                List<UserInfoBean.UserBean.RoleListBean> roleList = userBean.getRoleList();

                                if (roleList != null && roleList.size() > 0) {
                                    for (int i = 0; i < roleList.size(); i++) {
                                        String isLeader = roleList.get(i).getIsLeader(); //isLeader 1：职员 0：普通
                                        isLeaderList.add(isLeader);
                                    }

                                }

                                if (roleList != null && roleList.size() > 0) {
                                    UserInfoBean.UserBean.RoleListBean roleListBean = roleList.get(0);
                                    List<UserInfoBean.UserBean.RoleListBean.MenuAppListBean> menuAppListBean = roleListBean.getMenuAppList();
                                    if (menuAppListBean != null && menuAppListBean.size() > 0) {
                                        List<String> typeList = new ArrayList<>();
                                        for (int i = 0; i < menuAppListBean.size(); i++) {
                                            String path = menuAppListBean.get(i).getPath(); //isLeader 1：职员 0：普通
                                            typeList.add(path);
                                        }
                                        if (typeList.contains("/voice")) {
                                            voice = true;
                                        } else {
                                            voice = false;
                                        }
                                        //是否有下载图片、视频的权限
                                        if (typeList.contains("download")) {
                                            SPStaticUtils.put(SPTools.download, true);
                                        } else {
                                            SPStaticUtils.put(SPTools.download, false);
                                        }

                                        //控制户外屏的权限
                                        if (typeList.contains("outdoorControl")) {
                                            SPStaticUtils.put(SPTools.outdoorControl, true);
                                        } else {
                                            SPStaticUtils.put(SPTools.outdoorControl, false);
                                        }
                                    }
                                }

                                if (!StringUtils.isEmpty(mobile)) {
                                    SPStaticUtils.put(SPTools.mobile, mobile);//保存手机号
                                } else {
                                    SPStaticUtils.put(SPTools.mobile, "");
                                }
                                if (!StringUtils.isEmpty(name)) {
                                    SPStaticUtils.put(SPTools.userName, name);//保存用户名
                                } else {
                                    SPStaticUtils.put(SPTools.userName, "");
                                }

                                //是否是领导权限
                                if (isLeaderList.contains("1")) {
                                    SPStaticUtils.put(SPTools.isLeader, true);
                                } else {
                                    SPStaticUtils.put(SPTools.isLeader, false);
                                }

                                JPushInterface.setAlias(context, Constant.TYPE_BIND_ALIAS, username);
                                liteavInit();
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });


    }

    /**
     * 初始化实时视频
     */
    private void liteavInit() {
        //腾讯实时音视频
//        boolean tuiCalling = SPStaticUtils.getBoolean(MySPTools.TUI_CALLING);
//        if (!SPStaticUtils.contains(MySPTools.TUI_CALLING) || tuiCalling == false) {
        //每次都需要注册登录，不然会出现拨打错误
        getKeyInfo(new ResultCallback() {
            @Override
            public void result(Object object) {
                boolean b = Boolean.parseBoolean(object.toString());
                if (!b && StringUtils.isEmpty(sdkappid)) {
                    ToastUtils.showLong("实时音视频的key获取失败！");
                    return;
                }
                getUserSign(userName, mobile);
            }
        });
//        }

    }

    public boolean checkUserStatus() {
        String tip = "";
        if (mIsKickedOffline) {
            tip = getString(R.string.trtccalling_user_kicked_offline);
            ToastUtils.showShort(tip);

            JPushInterface.deleteAlias(context, Constant.TYPE_BIND_ALIAS);
            JPushUPSManager.turnOffPush(context, null);
        }
        if (mIsUserSigExpired) {
            tip = getString(R.string.trtccalling_user_sig_expired);
            ToastUtils.showShort(tip);
        }

        BasePopupView tipPopupView = new XPopup.Builder(MainActivity.this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .hasShadowBg(true)
                .asConfirm(context.getResources().getString(R.string.text_tip),
                        tip,
                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {

                                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), LoginActivity.class);
                                ActivityUtil.removeAllActivity();

                            }
                        }, null,
                        true);
        tipPopupView.show();


        SPStaticUtils.put(MySPTools.mIsKickedOffline, mIsKickedOffline);
        SPStaticUtils.put(MySPTools.mIsUserSigExpired, mIsUserSigExpired);
        return !mIsKickedOffline && !mIsUserSigExpired;
    }

    //获取实时音视频的userSig
    private void getUserSign(String userName, String myUserId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("message", myUserId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_USER_SIG + "/" + myUserId)
                .tag(this)
                .upJson(str)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                String sign = jsonObject.getString("sign");

                                final UserModel userModel = new UserModel();
                                userModel.phone = mobile;
                                userModel.userId = myUserId;
                                userModel.userName = TextUtils.isEmpty(userName) ? mobile : userName;
                                userModel.userAvatar = "";
                                userModel.userSig = sign;
                                UserModelManager.getInstance().setUserModel(userModel);


                                V2TIMSDKConfig config = new V2TIMSDKConfig();
                                config.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_DEBUG);

                                SPStaticUtils.put(MySPTools.mIsKickedOffline, false);
                                SPStaticUtils.put(MySPTools.mIsUserSigExpired, false);

                                TUILogin.init(BaseApplication.getBaseApplication(), Integer.parseInt(sdkappid), null, new V2TIMSDKListener() {

                                    @Override
                                    public void onKickedOffline() {
                                        mIsKickedOffline = true;
                                        checkUserStatus();

                                    }

                                    @Override
                                    public void onUserSigExpired() {
                                        mIsUserSigExpired = true;
                                        checkUserStatus();
                                    }
                                });
                                TUILogin.login(myUserId, sign, new V2TIMCallback() {
                                    @Override
                                    public void onError(int code, String msg) {
                                        MyLogUtil.e("MainActivity", "TUILogin  code: " + code + " msg:" + msg);
                                        SPStaticUtils.put(MySPTools.TUI_CALLING, false);
                                        ToastUtils.showLong("实时音视频功能获取失败！");
                                    }

                                    @Override
                                    public void onSuccess() {
                                        MyLogUtil.e("MainActivity", "TUILogin  onSuccess");
                                        SPStaticUtils.put(MySPTools.TUI_CALLING, true);

                                        V2TIMUserFullInfo v2TIMUserFullInfo = new V2TIMUserFullInfo();
                                        v2TIMUserFullInfo.setFaceUrl("");
                                        v2TIMUserFullInfo.setNickname(userName);
                                        V2TIMManager.getInstance().setSelfInfo(v2TIMUserFullInfo, new V2TIMCallback() {
                                            @Override
                                            public void onError(int code, String desc) {
                                                Log.e("MainActivity", "set profile failed errorCode : " + code + " errorMsg : " + desc);

                                            }

                                            @Override
                                            public void onSuccess() {
                                                Log.i("MainActivity", "set profile success.");
                                            }
                                        });

                                    }
                                });


                            } else {

                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });
    }

    //获取实时音视频的key和secretkey
    private void getKeyInfo(ResultCallback resultCallback) {
        OkGo.<String>get(MyConstant.GET_KEY_INFO)
                .tag(this)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                KeyBean keyBean = new KeyBean();
                                keyBean = gson.fromJson(result, KeyBean.class);
                                if (keyBean != null) {
                                    sdkappid = keyBean.getSdkappid();
                                    resultCallback.result(true);
                                    SPStaticUtils.put(MySPTools.TUI_APPID, sdkappid);
                                } else {
                                    resultCallback.result(false);
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                resultCallback.result(false);
                            }

                        }
                    }
                });
    }

    //腾讯IM 用来监听收到的消息（更新任务及通知相关逻辑）
    private void initIMListener() {
        V2TIMManager.getMessageManager().addAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
            @Override
            public void onRecvNewMessage(V2TIMMessage msg) {
                MyLogUtil.e("testtest", "onRecvNewMessage============" + msg.toString());
                if (msg != null) {
                    try {
                        indexFragment3.getTopEventNum();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onRecvMessageReadReceipts(List<V2TIMMessageReceipt> receiptList) {

            }

            @Override
            public void onRecvMessageRevoked(String msgId) {

            }

            @Override
            public void onRecvMessageModified(V2TIMMessage msg) {

            }
        });
    }

    /**
     * 自定义 NotificationChannel
     */
    private void initChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (nm != null) {
                NotificationChannelGroup notificationChannelGroup = new NotificationChannelGroup("MyGroupId", "自定义通知组");
                nm.createNotificationChannelGroup(notificationChannelGroup);

                NotificationChannel notificationChannel = new NotificationChannel("high_system", "自定义通知", NotificationManager.IMPORTANCE_HIGH);
                notificationChannel.setGroup("MyGroupId");
                notificationChannel.enableLights(true);
                notificationChannel.enableVibration(true);
                notificationChannel.setSound(Uri.parse("android.resource://" + AppUtils.getAppPackageName() + " /raw/phone_ringing.mp3"), null);    //设置自定义铃声

                nm.createNotificationChannel(notificationChannel);
            }
        }
    }

    private void initHa(String mobile, String userName) {
        String userNick = "thspatrol";
        if (!StringUtils.isEmpty(userName)) {
            userNick = userName;
        } else if (!StringUtils.isEmpty(mobile)) {
            userNick = mobile;
        }
        AliHaConfig config = new AliHaConfig();
        config.appKey = BuildConfig.EMAS_APP_KRY; //配置项：appkey
        config.appVersion = BuildConfig.VERSION_NAME;
        config.appSecret = BuildConfig.EMAS_APP_SECRET; //配置项：appsecret
        config.channel = "channel"; //配置项：应用的渠道号标记，自定义
        config.userNick = userNick; //配置项：用户的昵称
        config.application = getApplication(); //配置项：应用指针
        config.context = getApplicationContext(); //配置项：应用上下文
        config.isAliyunos = false; //配置项：是否为yunos
        config.rsaPublicKey = BuildConfig.TLOG_RSA_PUBLIC_LEY; //配置项：tlog公钥
        AliHaAdapter.getInstance().addPlugin(Plugin.tlog);
        AliHaAdapter.getInstance().addPlugin(Plugin.apm);
        AliHaAdapter.getInstance().openDebug(AppUtils.isAppDebug());
        AliHaAdapter.getInstance().start(config);
        TLogService.updateLogLevel(TLogLevel.DEBUG); //配置项：控制台可拉取的日志级别

    }

}
